#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<conio.h>
struct telephone{
 	char name[20];
 	char phonenumber[20];
 	telephone *next;//定义一个指向结构类型的指针
}*head,//链表头
*current,*ptr;//current表示当前链表，ptr是当前链表的前一个链表
void enter();
void del();
void list();
void search();
void save();
void load();

int main(){
	FILE *fp = fopen("books.txt", "r");
	int mode;
	

	do{
		printf("Choose your mode:\n\n");
		printf("0-退出通讯录\n");
		printf("1-通讯录录入\n");
		printf("2-通讯录删除\n");
		printf("3-通讯录显示\n");
		printf("4-通讯录查询\n");
		printf("5-通讯录保存\n");
		printf("6-通讯录加载\n");
		scanf("%d",&mode);
		system("cls");
		switch(mode){
			case 0:printf("已退出");
				break;
			case 1:enter();
				break;
			case 2:del();
				break;
			case 3:list();
				break;
			case 5:save();
				break;
			case 6:load();
		}
	}while(mode != 0);
 	return 0;
 }
 
 void enter(){
 	fflush(stdin);
	char input[20];
	//输入联系人
		printf("请输入联系人姓名：\n");
		while (gets(input) != NULL&&input[0] != '\0'){
			current = (telephone*)malloc(sizeof(telephone));
			if (head == NULL){
			 	head = current;
			}
			else{
				ptr->next = current;
			}
			current->next = NULL;
			
 			strcpy(current->name,input);
			printf("请输入电话号码：\n");
			scanf("%s", current->phonenumber);
			printf("请输入下一个联系人（空格结束）：\n");
			
			while (getchar() == '\n'){
			 	continue;
			}
			ptr = current;
			};
		system("cls");
		printf("已结束\n");
		
 }
 
 void del(){
 	;
 }
 
 void list(){
 	current = head;
	while (current != NULL){
		printf("%s:%s\n",current->name,current->phonenumber);
		current = current->next;
	};
	printf("显示完成\n");
 }
 
 void save(){
 	current = head;
	FILE *fp=fopen("book.txt","a");
	while (current != NULL){
		fprintf(fp,"%s %s\n",current->name,current->phonenumber);
		current = current->next;
	}
	//清除指针current的内存
	current = head;
	while (current != NULL){
	 	free(current);
		current = current->next;
	}
	fclose(fp);
//	printf("已保存");
	system("cls");
	printf("已保存/n");
 }
 
 void load(){
 	current = head;
	FILE *fp=fopen("book.txt","r");
	while (current != NULL){
		fscanf(fp,"%s%s",current->name,current->phonenumber);
		current = current->next;
	}
	fclose(fp);
	system("cls");
	printf("读取完成\n");
 }